package com.study.manage.mvc.org.authentication;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.TagRepository;
import com.study.manage.dal.UserOrganizaRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.domain.Tag;
import com.study.manage.domain.User;
import com.study.manage.domain.UserOrganiza;
import com.study.manage.domain.enumm.LiveDieState;
import com.study.manage.domain.enumm.UserOrganizaType;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.EmailDto;
import com.study.manage.dto.SessionUser;
import com.study.manage.exception.ManageException;
import com.study.manage.mvc.common.BaseController;
import com.study.manage.utils.Ids;
import com.study.manage.utils.MapUtils;

@Controller
@RequestMapping("org/acc")
@Scope("request")
public class RZController extends BaseController {

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private UserOrganizaRepository userOrganizaRepository;

    @Autowired
    private RZService service;

    @Autowired
    private TagRepository tagRepository;

    @RequestMapping(path = "authentication", method = RequestMethod.GET)
    public String index(ModelMap model) {
    	
        SessionUser su = (SessionUser) session.getAttribute("user");
        List<Tag> tags = tagRepository.findByStateOrderBySquenAsc(LiveDieState.LIVE);
        model.put("tags", jsonMapper.toJson(tags));
        User user = userRepository.findOne(su.getId());
        UserOrganiza uo = userOrganizaRepository.findByRegUserId(user.id);
        Map<String, Object> map = MapUtils.convert(uo == null ? new UserOrganiza() : uo);
        map.put("phone", user.phone);
        model.put("data", jsonMapper.toJson(map));
        return "org/acc/authentication";
    }

    @ResponseBody
    @RequestMapping(path = "getCode", method = RequestMethod.GET)
    public AjaxResponse getCode(String phone) throws Exception {
    	
    	AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = (SessionUser) session.getAttribute("user");
        //当是微信登陆时
        if (su.getPhone() == null) {
            User u = userRepository.findByPhone(phone);
            if (u != null) {
                throw new ManageException("手机号已经存在");
            }
        }
        sendPhoneCode("CODE_NAME",phone);
        return ajax;
    }
    
    @ResponseBody
    @RequestMapping(path = "save_authentication", method = RequestMethod.POST)
    public AjaxResponse index_save(RZForm form , ModelMap model) {
    	
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = (SessionUser) session.getAttribute("user");
        String sCode = (String) request.getSession().getAttribute(CODE_NAME);
        if(EmailDto.checkPhoneCode(sCode,form.getCode())) {
        	ajax.setSuccess(false);
        	return ajax.setMsg("手机验证码错误").setCode("002");
        };
        UserOrganiza uo = (UserOrganiza) this.getRequestParameter(request, UserOrganiza.class);
        if (uo.type == UserOrganizaType.Work) {
        	if(uo.idImg1==null || uo.idImg2==null){
        		ajax.setSuccess(false);
            	return ajax.setMsg("请上传身份证照片").setCode("002");
        	}
        } else if (uo.type == UserOrganizaType.Company) {
        	if(form.getLicenseImg2()==null){
        		ajax.setSuccess(false);
            	return ajax.setMsg("请上传营业执照").setCode("002");
        	}
            uo.idName = form.getIdName2();
            uo.fullName =form.getFullName2();
            uo.mailAddress = form.getMailAddress2();
            uo.licenseNumber =form.getLicenseNumber2();
            uo.licenseImg =form.getLicenseImg2();
        } else if (uo.type == UserOrganizaType.School) {
        	if(form.getLicenseImg3()==null){
        		ajax.setSuccess(false);
            	return ajax.setMsg("请上传证件照").setCode("002");
        	}
            uo.idName = form.getIdName3();
            uo.fullName =form.getFullName3();
            uo.mailAddress = form.getMailAddress3();
            uo.licenseNumber =form.getLicenseNumber3();
            uo.licenseImg = form.getLicenseImg3();
        }
        uo.tags = form.getTagId();
        uo.email = "";
        service.rz(su.getId(), uo);
        
        //设置密码
        User zUser = userRepository.findOne(su.getId());
        zUser.salt = Ids.randomBase62(64);
        zUser.hashPassword = hashPassword(form.getPassword(), scret, zUser.salt);
        //设置手机号
        if (zUser.phone == null) {
        	zUser.phone = form.getPhone();
        }
        userRepository.save(zUser); 
        ajax.setSuccess(true);
        return ajax;
    }

    @RequestMapping(path = "success", method = RequestMethod.GET)
    public String success(HttpServletRequest request, ModelMap model) {
    	
        return "org/acc/success";
    }

}
